local net = require("framework.cc.net.init")
-- local Timer = require("utils.Timer")
local crypt = require "crypt"

local LoginScene = class("LoginScene", function()
  print("+++++++")
    return display.newScene("LoginScene")
end)

-- local function onButtonClicked(event)

--         if event.buttonIndex == 1 then

--             print("玩家选择了 YES 按钮")

--         else

--             print("玩家选择了 NO 按钮")

--         end

--     end

local nameET,passET
function LoginScene:ctor()

local bg = display.newSprite("login_bg.png",display.cx,display.cy)
bg:setScaleX(display.width/bg:getContentSize().width)
bg:setScaleY(display.height/bg:getContentSize().height)
bg:addTo(self)


	  cc.ui.UILabel.new({
           UILabelType = 2, text = "南通长牌", font="fonts/fzcyt.ttf",size = 64})
       :align(display.CENTER, display.cx, display.cy+100)
       :addTo(self)

       nameET = cc.ui.UIInput.new({
        image = "EditBoxBg.png",
        size = cc.size(400, 50),
        x = display.cx,
        y = display.cy,
        listener = function(event, editbox)
          	-- if event == "changed" then
           --      self:onEditBoxChanged(editbox)
           --  else
           --      printf("EditBox event %s", tostring(event))
           --  end
        end
    })
    nameET:setPlaceHolder("请输入用户名")
    nameET:setReturnType(cc.KEYBOARD_RETURNTYPE_SEND)
    nameET:setText("test")
    self:addChild(nameET)

	  passET = cc.ui.UIInput.new({
	    image = "EditBoxBg.png",
	    size = cc.size(400, 50),
      placeHolder = "",
      text = "123456",
	    x = display.cx,
	    y = display.cy-60,
	    listener = function(event, editbox)
	      	-- if event == "changed" then
	       --      self:onEditBoxChanged(editbox)
	       --  else
	       --      printf("EditBox event %s", tostring(event))
	       --  end
	    end
	})
    passET:setReturnType(cc.KEYBOARD_RETURNTYPE_SEND)
    passET:setInputFlag(0)
    passET:setPlaceHolder("请输入密码")
    passET:setText("123456")
    self:addChild(passET)

	cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
    :setButtonSize(100, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "登录"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
    	self.loginAction()
    end)
    :pos(display.cx+150, display.cy-120)
    :addTo(self)


local loadBar = cc.ui.UILoadingBar.new({
    scale9 = true,
    capInsets = cc.rect(0,0,10,10), -- scale region
    image =  "btn_orange.png", -- loading bar image
    viewRect = cc.rect(0,0,200,32), -- set loading bar rect
    percent = 30, -- set loading bar percent
    -- direction = DIRECTION_RIGHT_TO_LEFT
    -- direction = DIRECTION_LEFT_TO_RIGHT -- default
})

:addTo(self)

    -- display.addSpriteFrames("game.plist", "game.png")

    -- self.takeBtn = cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
    -- self.takeBtn:setButtonSize(100, 40)
    -- :setButtonLabel(cc.ui.UILabel.new({text = "出牌"}))
    -- :onButtonPressed(function(event)
    --     event.target:setScale(1.1)
    -- end)
    -- :onButtonRelease(function(event)
    --     event.target:setScale(1.0)
    -- end)
    -- :onButtonClicked(function()
    --     if self.playFlag then
    --       self:play()
    --    else
    --       self:take()
    --    end
    -- end)
    -- :pos(display.width-120, display.cy-120)
    -- :addTo(self)
    -- self.playFlag = true
    -- self:test()
    -- self:palyerInit()
        -- device.showAlert("Confirm Exit", "Are you sure exit game ?", {"YES", "NO"}, onButtonClicked)

  --     display.addSpriteFrames("game.plist", "game.png")
    -- local args = {ok =1,userid="test"}
    -- app:createView("GameResultView",args)
    -- :pos(0,0)
    -- :addTo(self)

    -- app:createView("CreateRoomView",function(name)
    --         end)
    --         :pos(0,0)
    --         :addTo(self)
end

function LoginScene:onEnter()

end

function LoginScene:onExit()
end

function LoginScene:onEditBoxChanged(editbox)
    printf("editBox1 event changed : %s", editbox:getText())
end

local scnet = {}

function scnet.tcpConnected()
  	scnet.connected = true
end

local function unpack_line(text)
  local from = text:find("\n", 1, true)
  if from then
    return text:sub(1, from-1), text:sub(from+1)
  end
  return nil, text
end


local oneLine=""
local challenge
local clientkey

local function encode_token(token)
  return string.format("%s@%s:%s",
    crypt.base64encode(token.user),
    crypt.base64encode(token.server),
    crypt.base64encode(token.pass))
end

function scnet.challenge(args)
    print("challenge:",args)
    challenge = crypt.base64decode(args)
     clientkey = crypt.randomkey()
    scnet.socket:send(crypt.base64encode(crypt.dhexchange(clientkey)).."\n")
end

function scnet.secret(args)
  local secret = crypt.dhsecret(crypt.base64decode(args), clientkey)
  print("sceret is ", crypt.hexencode(secret))
  local hmac = crypt.hmac64(challenge, secret)
  scnet.socket:send(crypt.base64encode(hmac).."\n")

  local name = nameET:getText()
  local pass = passET:getText()
  local token = {
    server = "gate1",
    user = name,
    pass = pass,
  }
  local etoken = crypt.desencode(secret, encode_token(token))
  scnet.socket:send(crypt.base64encode(etoken).."\n")
end

local function mainScene(subid)
  print(subid,"------")
    app:enterScene("MainScene", {subid}, "fade", 0.6, display.COLOR_WHITE)
    scnet.socket:close()
end 

function scnet.code(args)
local code = tonumber(string.sub(args, 1, 3))
  if code == 200 then
    local subid = crypto.decodeBase64(string.sub(args, 5))
     mainScene(subid)
  elseif code == 406 then
     mainScene()
  else
      print("失败")
  end
end


function scnet.receive(event)
  oneLine = oneLine..event.data
  while true and oneLine ~=nil and string.len(oneLine)>0 do
	 local from = oneLine:find("\n", 1, true)
   if from then
      local data = oneLine:sub(1, from-1)
      print(data)
      local f, args = string.match(data, "([^:]*):([^:]*)")
      print(f,":",args)
      scnet[f](args)
      oneLine=oneLine:sub(from+1)
     -- print("data1:",oneLine)
   else 
      break
    end
 end
end

function LoginScene:loginAction()

 	-- if scnet.socket and  scnet.connected then 
 	-- 	scnet.doLogin(name,pass)
 	-- 	return
 	--  end
    scnet.socket = net.SocketTCP.new()
     scnet.socket:addEventListener(net.SocketTCP.EVENT_CLOSED, function()
         scnet.connected = false
    end)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_CONNECT_FAILURE, function()
       	scnet.connected = false
    end)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_CONNECTED, scnet.tcpConnected)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_DATA, scnet.receive)

   local ip,port = string.match(LOGIN_IP,"([^:]+):(.+)")
    scnet.socket:connect(ip,port)
end

return  LoginScene